package com.sso.controller.auth;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sso.bean.entity.User;
import com.sso.controller.BaseController;
import com.sso.service.AuthTicketService;
import com.sso.service.impl.AuthTicketServiceImpl.AuthTicketFactory;

@Controller
@RequestMapping("/ssoAuth")
public class AuthticationController  extends BaseController {
    
    @Resource(name = "authService") 
    AuthTicketService authService;
    
    private static final Logger LOG = LoggerFactory.getLogger(AuthticationController.class);
    
    @RequestMapping("/login")
    public void login(HttpServletRequest request, HttpServletResponse response,
            @RequestParam(value = "serviceUrl", required = false) String serviceUrl,
            @RequestParam(value = "authUrl", required = false) String authUrl) {
        String tgc = getCookieTGC(request);
        String custNum = getCookieCustNum(request);
        //kernel级cookie, 共同表示用户已经登陆
        if (StringUtils.isNotBlank(tgc) && StringUtils.isNotBlank(custNum)) { //登录过
        	User user = authService.getUserById(Long.valueOf(custNum));
        	if (null != user && tgc.equals(user.getTgc())) {
        		//do redirect
        		redirect2Client(response, serviceUrl, authUrl, user);
        		return;
        	}
        }
        request.setAttribute("serviceUrl", serviceUrl);
        request.setAttribute("authUrl", authUrl);
        try {
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}  catch (Exception e) {
            LOG.error("exception occur when method {} dispatcher to login.jsp.", "login()");
            return;
        }
        return;
    }
    
    @RequestMapping("/validation")
    @ResponseBody
    public Object validation(HttpServletRequest request, HttpServletResponse response,
    		@RequestParam(value = "ticket", required = false) String ticket) throws IOException {
    	Map<String,Object> map = new HashMap<String, Object>();
    	User user = authService.validationTicket(ticket);
    	if (null == user) {
    		map.put("retCode", 0);
    		return map;
    	} else {
    		map.put("retCode", 1);
    		map.put("userInfo", user);
    		return map;
    	}
        
    }
    
    @RequestMapping("/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        
    }
    
    @RequestMapping("/doLogin")
    public void doLogin(HttpServletRequest request, HttpServletResponse response,
            @RequestParam(value = "serviceUrl", required = true) String serviceUrl,
            @RequestParam(value = "authUrl", required = true) String authUrl,
            @RequestParam(value = "username", required = true) String username,
            @RequestParam(value = "password", required = true) String password) {
        //TODO check login user's account
    	User user = authService.getUserByUsernameAndPassword(username, password);
        if (null == user) {
            try {
                request.setAttribute("loginWarningDiv", "<div class='alert alert-info'>登录失败！</div>");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
                return;
            } catch (Exception e) {
                LOG.error("exception occur when method {} dispatcher to login.jsp.", "doLogin()");
                return;
            }
        }
        
        Cookie tgt_Cookie = new Cookie(TICKET_GRANTING_TICKET_COOKIE_NAME, authService.createTgc(user.getId()));
        Cookie custno_Cookie = new Cookie(CUST_NUM_COOKIE_NAME, String.valueOf(user.getId()));
        int expire = -1;
        tgt_Cookie.setMaxAge(expire);
        custno_Cookie.setMaxAge(expire);
        response.addCookie(tgt_Cookie);
        response.addCookie(custno_Cookie);
        redirect2Client(response, serviceUrl, authUrl, user);
        return;
    }

	private void redirect2Client(HttpServletResponse response, String serviceUrl, String authUrl, User user) {
        
        try {
            PrintWriter writer = response.getWriter();
            writer.print("<script type='text/javascript'>");
            writer.print("document.write(\"<form id='authUrl' action='" + authUrl + "'>\");");
			writer.print("document.write(\"<input type='hidden' name='ticket' value='" + AuthTicketFactory.getTicket(user) + "' />\");");
			writer.print("document.write(\"<input type='hidden' name='serviceUrl' value='" + serviceUrl + "' />\");");
			writer.print("document.write('</form>');");
			writer.print("document.getElementById('authUrl').submit();");
			writer.print("</script>");
            return;
        } catch (IOException e) {
            LOG.error("exception occur when method {} get response writer.", "doLogin()");
        }
	}
    
}
